package com.peng.mybatis.session.defaults;

import cn.hutool.db.transaction.TransactionLevel;
import com.peng.mybatis.executor.Executor;
import com.peng.mybatis.mapping.Environment;
import com.peng.mybatis.session.Configuration;
import com.peng.mybatis.session.SqlSession;
import com.peng.mybatis.session.SqlSessionFactory;
import com.peng.mybatis.transaction.Transaction;
import com.peng.mybatis.transaction.TransactionFactory;

import java.sql.SQLException;

public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private final Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public SqlSession openSession() {
        Transaction transaction = null;
        try {
            Environment environment = configuration.getEnvironment();
            TransactionFactory transactionFactory = environment.getTransactionFactory();
            transaction = transactionFactory.newTransaction(environment.getDataSource(),
                    TransactionLevel.READ_COMMITTED, false);
            Executor executor = configuration.newExecutor(transaction);
            return new DefaultSqlSession(configuration, executor);
        } catch (SQLException e) {
            try {
                assert transaction != null;
                transaction.close();
            } catch (SQLException ignored) {

            }
            throw new RuntimeException("开启会话失败:" + e.getMessage(), e);
        }
    }

}
